from django import shortcuts
from google.appengine.api import memcache
import settings
from tweepy import *
from tweepy import BasicAuthHandler
from tweepy.api import API
from tweepy.auth import OAuthHandler
import re

auth_handler = OAuthHandler(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
app_settings = { 
                'rt': '{cursor} RT @{user}: {content}',
                'css': '',
                'filters': '',
                'auto_show_content': False
                }

def get_api(request):
    if 'oauth' in request.COOKIES:
        auth_handler.set_access_token(request.COOKIES['oauth_key'], request.COOKIES['oauth_secret'])
        api = API(auth_handler)
        return api
    elif 'user' in request.COOKIES and 'pwd' in request.COOKIES:
        handler = BasicAuthHandler(request.COOKIES['user'], request.COOKIES['pwd'])
        api = API(handler, host=settings.TWITTER_HOST, api_root=settings.TWITTER_API_ROOT)
        return api

def respond(request, template, params=None):
    if params is None:
        params = {}
    params['settings'] = load_settings(request)
    params['base_url'] = settings.BASE_URL
    if 'user' in request.COOKIES:
        params['screen_name'] = request.COOKIES['user']
    if not template.endswith('.html'):
        template += '.html'
    return shortcuts.render_to_response(template, params)

def get_cached_verify_credentials(request):
    key = "%s_%s" % (request.COOKIES['user'], '.verify_cridentials')
    #data = memcache.get(key)
    '''Temp: don't cache verify credentials for now'''
    data = None
    if data is None:
        api = get_api(request)
        data = api.verify_credentials()
        memcache.add(key, data, 60 * 10)
    return data

def clear_memcache(request):
    keys = ['verify_cridentials']
    memcache.delete_multi(keys, key_prefix=request.COOKIES['user'])

def load_settings(request):
    for key in app_settings:
        cookie_key = 'setting_' + key
        if cookie_key in request.COOKIES:
            app_settings[key] = request.COOKIES[cookie_key]
    return app_settings

def save_settings(request, response):
    for key in app_settings:
        if key in request.POST:
            response.set_cookie('setting_%s' % key, request.POST[key].encode("utf-8"))

def filter_with_keyword(statuses, keywords):
    pattern = re.compile('[%s]' % '|'.join(keywords))
    return [status for status in statuses if pattern.match(status.text) is not None]
